<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue"
import { ElMessage } from "element-plus"
import { useFormRules, useFormValid } from "../useLogin"
import { useUserStore } from "../../../store/modules/user"
import { getTenantIdByName, } from "../../../api/login"
import { setTenantId } from "../../../utils/auth"
import { Verify } from "../../../components/Verifition"
import { User, Lock, OfficeBuilding } from '@element-plus/icons-vue'

const userStore = useUserStore()
const loading = ref(false)
// @ts-ignore
const tenantEnable = ref(window.__VITE_TENANT_ENABLE__ === "true")

const formRef = ref()
const { validForm } = useFormValid(formRef)
const { usernameRule, passwordRule, tenantNameRule } = useFormRules()

// 验证码相关变量
const verify = ref()

const formData = reactive({
  tenantName: "", // 默认租户名
  username: "",
  password: "",
  captchaVerification: "",
})

// 页面加载时从localStorage获取之前保存的用户名和密码
onMounted(() => {
  const savedUsername = localStorage.getItem("savedUsername")
  const savedPassword = localStorage.getItem("savedPassword")
  const saveTenantName = localStorage.getItem("saveTenantName")

  if (savedUsername) {
    formData.username = savedUsername
  }

  if (savedPassword) {
    formData.password = savedPassword
  }

  if (saveTenantName) {
    formData.tenantName = saveTenantName
  }
})

// 获取租户ID
async function getTenantId() {
  try {
    const res = await getTenantIdByName(formData.tenantName)
    setTenantId(res)
  } catch (error) {
    ElMessage.error("获取租户信息失败，请检查租户名称")
  }
}

// 验证码验证成功后处理登录
async function handleCaptchaSuccess(params: any) {
  try {
    const data = await validForm()
    if (!data) return

    formData.captchaVerification = params.captchaVerification

    // 获取租户ID
    await getTenantId()

    loading.value = true
    const userInfo = await userStore.login({
      username: formData.username,
      password: formData.password,
      captchaVerification: formData.captchaVerification,
      mode: "modal",
    })

    if (userInfo) {
      // 保存用户名和密码到localStorage
      if (formData.username) {
        localStorage.setItem("savedUsername", formData.username)
      } else {
        localStorage.removeItem("savedUsername")
      }

      if (formData.password) {
        localStorage.setItem("savedPassword", formData.password)
      } else {
        localStorage.removeItem("savedPassword")
      }
      if (formData.password) {
        localStorage.setItem("saveTenantName", formData.tenantName)
      } else {
        localStorage.removeItem("saveTenantName")
      }
      ElMessage.success("登录成功")
      // 等待俩秒
      setTimeout(() => {
        window.location.reload()
      },800)
    }
  } catch (error) {
    console.error("登录失败:", error)
    ElMessage.error("登录失败，请检查用户名和密码")
  } finally {
    loading.value = false
  }
}

// 登录按钮点击处理 - 显示验证码
async function handleLogin() {
  // 先验证表单
  const data = await validForm()
  if (!data) return

  // 弹出验证码
  verify.value.show()
}

// 用户名为空时移除localStorage
function removeUsernameFromStorage() {
  if (!formData.username) {
    localStorage.removeItem("savedUsername")
  }
}

// 密码为空时移除localStorage
function removePasswordFromStorage() {
  if (!formData.password) {
    localStorage.removeItem("savedPassword")
  }
}
</script>

<template>
  <div class="login-form">
    <el-form ref="formRef" :model="formData" label-position="top" @keyup.enter="handleLogin">
      <!-- 租户名输入 -->
      <el-form-item v-if="tenantEnable" prop="tenantName" :rules="tenantNameRule">
        <el-input v-model="formData.tenantName" placeholder="请输入租户名称" size="large">
          <template #prefix>
            <el-icon><OfficeBuilding /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 用户名输入 -->
      <el-form-item prop="username" :rules="usernameRule">
        <el-input v-model="formData.username" placeholder="请输入用户名" size="large" @input="removeUsernameFromStorage">
          <template #prefix>
            <el-icon><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 密码输入 -->
      <el-form-item prop="password" :rules="passwordRule">
        <el-input v-model="formData.password" type="password" placeholder="请输入密码" size="large" show-password @input="removePasswordFromStorage">
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 登录按钮 -->
      <el-button type="primary" class="login-button" size="large" :loading="loading" @click="handleLogin"> 登录 </el-button>
    </el-form>

    <!-- 验证码组件 -->
    <Verify ref="verify" mode="pop" captchaType="blockPuzzle" :img-size="{ width: '400px', height: '200px' }" @success="handleCaptchaSuccess" />
  </div>
</template>

<style lang="less" scoped>
.login-form {
  .login-button {
    width: 100%;
    margin-bottom: 16px;
  }
}
</style>

